#include "ImaUtils.h"
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <ctype.h>

bool ImaUtils::isValidEmailAddress(const char *pEmailAddress) {
	if(!pEmailAddress) // If cannot read the Email Address...
		return 0;
	if(!isCharacter(pEmailAddress[0])) // If the First character is not A-Z, a-z
		return 0;
	int AtOffset = -1;
	int DotOffset = -1;
	unsigned int Length = strlen(pEmailAddress); // Length = StringLength (strlen) of EmailAddress
	for(unsigned int i = 0; i < Length; i++) {
		if(pEmailAddress[i] == '@') // If one of the characters is @, store it's position in AtOffset
			AtOffset = (int)i;
		else if(pEmailAddress[i] == '.') // Same, but with the dot
			DotOffset = (int)i;
	}
	if(AtOffset == -1 || DotOffset == -1) // If cannot find a Dot or a @
		return 0;
	if(AtOffset > DotOffset) // If the @ is after the Dot
		return 0;
	return !(DotOffset >= ((int)Length-1)); //Chech there is some other letters after the Dot
}

void ImaUtils::toLower(char* pStr) {
   if(pStr == NULL) {
      return;
   }

   for(int i = 0; pStr[i]; i++){
      pStr[i] = tolower(pStr[i]);
   }
}

bool ImaUtils::isPermittedImService(const char* pImService) {
	if((strcmp(pImService, "gmail.com") == 0) 
		|| (strcmp(pImService, "iamaliv.com") == 0)) {
		return true;
	}

	return false;
}

bool ImaUtils::isValidImId(const char* pImId) {
   if(ImaUtils::isValidEmailAddress(pImId)) {
		char imId[128];
		strcpy(imId, pImId);
      char* p = strstr(imId, "@");
      char imService[128];
      strcpy(imService, p+1);
      ImaUtils::toLower(imService);

		return ImaUtils::isPermittedImService(imService);
	}

	return false;
}


bool ImaUtils::isValidPhoneNum(const char* pPhoneNUm) {
	//TODO:
	return true;
}

void ImaUtils::genRandomKey(char *s, const int len) {
    static const char alphanum[] =
        "0123456789"
        "abcdefghijklmnopqrstuvwxyz";

    for (int i = 0; i < len; ++i) {
        s[i] = alphanum[rand() % (sizeof(alphanum) - 1)];
    }

    s[len] = 0;
}

int ImaUtils::getFileContents(char* pFilename, char** pBuffer) {
	char *source = NULL;
	long bufsize=0;
	FILE *fp = fopen(pFilename, "r");
	if (fp != NULL) {
		/* Go to the end of the file. */
		if (fseek(fp, 0L, SEEK_END) == 0) {
   		/* Get the size of the file. */
			bufsize = ftell(fp);
			if (bufsize == -1) {
			 /* Error */
			   return -1;
			}

		   /* Allocate our buffer to that size. */
			source = (char*)malloc(sizeof(char) * (bufsize + 1));
			
			/* Go back to the start of the file. */
			if (fseek(fp, 0L, SEEK_SET) == 0) { /* Error */ }
			
			/* Read the entire file into memory. */
			size_t newLen = fread(source, sizeof(char), bufsize, fp);
			if (newLen == 0) {
				fputs("Error reading file", stderr);
			} else {
				source[++newLen] = '\0'; /* Just to be safe. */
			}
		}
		fclose(fp);
	}
	*pBuffer = source;

	return bufsize + 1 ;
}
